package com.newlink.building.main.other

import android.util.Log
import com.newlink.building.common_base.event.CallSipBean

/**
 * Created by xiaodong on 2024/8/19.
 */
object Module_Main_SipMessageUtils {
    fun parseSipMessage(jsonBody: String): Module_Main_SipMessage? {
        val sipMessage = Module_Main_SipMessage()
        val lines: List<String> = jsonBody.split("\r\n")
        //SIP版本号
        val sipVersion = "SIP/2.0 "
        //SIP版本号 兼容IOS对字符串转义处理
        val sipVersionIOS = "SIP\\/2.0 "
        //sip协议类型
        val sessionProtol = arrayOf("INVITE", "ACK", "CANCEL", "BYE", "UPDATE")

        try {
            for ((index, line) in lines.withIndex()) {
                //解析首行 SIP消息的类型
                if (index == 0) {
                    if (line.startsWith(sipVersion)) {//适配IOS json格式
                        // 处理状态行 e.g SIP/2.0 200 OK\r\n
                        sipMessage?.sipMethod = line.split(sipVersion)[1].trim()
                    } else if (line.startsWith(sipVersionIOS)) {
                        // 处理状态行 适配IOS e.g SIP\/2.0 200 OK\r\n
                        sipMessage?.sipMethod = line.split(sipVersionIOS)[1].trim()
                    } else {
                        // 处理协议类型
                        sessionProtol.forEach {
                            if (line.startsWith(it)) {
                                sipMessage?.sipMethod = it
                            }
                        }
                    }

                } else {
                    if (line.contains(": ")) {
                        // 处理头部
                        val headers = line.split(": ")
                        val header = headers[0]
                        val value = headers[1]
//                        val headerMaps = mapOf(header[0] to header[1])
                        //只解析部分字段,需要的话再扩充

                        header?.let {
                            when (it) {
                                "Call-ID" -> {
                                    sipMessage?.callId = value
                                }

                                "CSeq" -> {
                                    sipMessage?.cseq = value
                                }

                                "P-Early-Media" -> {
                                    if (value == "supported" && jsonBody.contains("sendonly")) {
                                        sipMessage?.enableEarlyMedia = true
                                    }
                                }

//                                "From" -> {
//                                    sipMessage?.from = value
//                                }
//
//                                "To" -> {
//                                    sipMessage?.to = value
//                                }
                            }
                        }
                    }
                }
            }
            return sipMessage
        } catch (e: Exception) {
            Log.e("[SipMessageUtils]", "$e")
            return null
        }
        return sipMessage
    }

    fun parseSimpleSipMessage(
        callSipBean: CallSipBean,
        sipMessage: Module_Main_SipMessage?,
        basicTimeStamp: Long
    ): Module_Main_SimpleSipMessage {

        val currentTimeMillis = System.currentTimeMillis()
        return Module_Main_SimpleSipMessage(
            type = sipMessage?.sipMethod.orEmpty(),
            callId = sipMessage?.callId.orEmpty(),
            cseq = sipMessage?.cseq.orEmpty(),
            cn = callSipBean.channelName,
            from = callSipBean.from,
            to = callSipBean.to,
            duration = currentTimeMillis - basicTimeStamp
        )
    }

    /**
     * 来电事件 收到INVITE
     */
    fun incomingCallEvent(sipMessage: Module_Main_SipMessage?, toAid: String, agoraId: String): Boolean {
        return sipMessage?.sipMethod == "INVITE" && toAid == agoraId
    }

    /**
     * 去电状态 包括 100 Trying / 180 Ring / 200 ok
     */
    fun outgoingCallEvent(sipMessage: Module_Main_SipMessage?, fromAid: String, agoraId: String): Boolean {
        if (fromAid != agoraId) return false
        if (receive100Trying(sipMessage) || receive180Ringing(sipMessage) || receive200Ok(sipMessage)) {
            return true
        }
        return false
    }

    fun receive100Trying(sipMessage: Module_Main_SipMessage?): Boolean {
        return sipMessage?.sipMethod == "100 Trying" && sipMessage.cseq.contains("INVITE")
    }

    fun receive180Ringing(sipMessage: Module_Main_SipMessage?): Boolean {
        return sipMessage?.sipMethod == "180 Ringing" && sipMessage.cseq.contains("INVITE")
    }

    fun receive200Ok(sipMessage: Module_Main_SipMessage?): Boolean {
        return sipMessage?.sipMethod == "200 OK" && sipMessage.cseq.contains("INVITE")
    }

    fun receiveByeEvent(sipMessage: Module_Main_SipMessage?): Boolean {
        return sipMessage?.sipMethod == "200 OK" && sipMessage.cseq.contains("BYE")
    }

}